<template>
  <div class="login-setting">
    账号设置
    <el-form ref="userForm" :model="userInfo" :rules="rules" label-width="120px" style="margin-left:120px;margin-top:30px">
      <el-form-item label="姓名:" prop="username">
        <el-input v-model="userInfo.username" style="width:300px" />
      </el-form-item>
      <el-form-item label="密码:" prop="password">
        <el-input v-model="userInfo.password" type="password" style="width:300px" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submit">更新</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { getUserDetailById, saveUserDetailById } from '@/api/user'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getsuerInfo()
  },
  methods: {
    async getsuerInfo() {
      const res = await getUserDetailById(this.$route.query.id)
      console.log('获取用户信息', res)
      // 数据回填

      // this.userInfo.username = res.data.username
      // this.userInfo.password = res.data.password
      this.userInfo = res.data
    },
    // 修改员工信息的方法
    async doEdit() {
      // 接口文档中有错误：saveUserDetailById这个接口要求我们传入所有的字段(请求的类型是 PUT，是要全量修改)，如果不传入它就会置空
      // 所以将上方获取的数据的值都赋值给userInfo
      try {
        const res = await saveUserDetailById(this.userInfo)
        console.log(res)
        this.$message.success('修改成功')
      } catch (err) {
        console.log(err)
        this.$message.warning('修改失败')
      }
    },
    // 点击提交要有兜底校验
    submit() {
      this.$refs.userForm.validate(valid => {
        if (valid) {
          this.doEdit()
        }
      })
    }
  }
}
</script>
